package yxy.game.pm2.active.module;

import org.redisson.api.RMap;
import yxy.apple.util.redisson.RedisException;
import yxy.cherry.game.base.redis.RedisManager;
import yxy.game.pm2.bean.db.newDao.ActOpenDAO;
import yxy.game.pm2.bean.db.po.ActOpenPo;
import yxy.game.pm2.bean.module.BaseGameRedisLockBean;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ActOpenModule extends BaseGameRedisLockBean {
	
	// redis==========================================================================
	static public String key(String playerCode) {
		return String.format("PLAYER:%s:MODULE:ACTOPEN", playerCode);
	}

	static private RMap<Integer, Integer> touch(String playerCode) throws RedisException {
		return RedisManager.client(redis()).getMap(key(playerCode));
	}

	public static Integer get(String playerCode, int acttype) {
		try {
			return touch(playerCode).get(acttype);
		} catch (Exception e) {
		}
		return 0;
	}

	public static void set(String playerCode, int acttype, int state) {
		try {
			touch(playerCode).put(acttype, state);
		} catch (RedisException e) {
		}
	}

	public static Map<Integer, Integer> all(String playerCode) {
		try {
			Map<Integer, Integer> bucket = touch(playerCode).readAllMap();

			if(bucket.isEmpty()){
				List<ActOpenPo> actOpenPos = ActOpenDAO.getList(playerCode);

				if(actOpenPos != null && actOpenPos.size() > 0) {
					for (int i = 0; i < actOpenPos.size(); i++) {
						bucket.put(actOpenPos.get(i).getDataId(),actOpenPos.get(i).getValue());
					}
				}
			}

			return bucket;
		} catch (RedisException e) {
			e.printStackTrace();
		}
		return new HashMap<>();
	}

	//数据归档到数据库
	public static void saveToDB(String playerCode) {
		try {
			//存储
			List<ActOpenPo> actOpenPos = new ArrayList<>();
			RMap<Integer, Integer> rMap = touch(playerCode);
			if (rMap.isExists()) {
				Map<Integer, Integer> touch = rMap.readAllMap();
				for (Map.Entry<Integer, Integer> entry : touch.entrySet()) {
					int key = entry.getKey();
					int value = entry.getValue();
					ActOpenPo actOpenPo = new ActOpenPo();
					actOpenPo.setPlayerCode(playerCode);
					actOpenPo.setDataId(key);
					actOpenPo.setValue(value);
					actOpenPos.add(actOpenPo);

					ActOpenDAO.replace(actOpenPos);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	//从redis移走数据
	public static void removeAllFromRedis(String playerCode) {
		try {
			touchBucket(key(playerCode)).delete();
		} catch (RedisException e) {
			e.printStackTrace();
		}
	}
}
